package com.rpc.register;

import com.rpc.framework.URL;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 注册中心
 * @Author:cxy
 * @Date:2021/1/21 20:50
 */
public class RemoteMapRegister {

    private static Map<String, List<URL>> REGIEST_MAP = new ConcurrentHashMap<>();


    /**
     * 注册服务
     * @param interfaceName 接口名称
     * @param url 一台机器一个服务
     */
    public static void regist(String interfaceName,URL url){
        List<URL> urls = REGIEST_MAP.get(interfaceName);
        if(urls == null){
            urls = new ArrayList<>();
        }
        urls.add(url);
        REGIEST_MAP.put(interfaceName,urls);
        saveFile();
    }

    /**
     * 获取服务
     * @param interfaceName 接口名
     * @return 服务列表
     */
    public static List<URL> getServerUrls(String interfaceName){
        REGIEST_MAP = getFile();
        return REGIEST_MAP.get(interfaceName);
    }


    /**
     * 存储redis 或者文件
     */
    public static void saveFile(){
        try {
            final FileOutputStream outputStream = new FileOutputStream("/REGIEST_MAP.text");
            final ObjectOutputStream stream = new ObjectOutputStream(outputStream);
            stream.writeObject(REGIEST_MAP);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static Map<String, List<URL>> getFile(){
        try {
            final FileInputStream fileInputStream = new FileInputStream("/REGIEST_MAP.text");
            final ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            final Map<String, List<URL>> map = (Map<String, List<URL>>) objectInputStream.readObject();
            return map;
        }catch (IOException | ClassNotFoundException e){
            e.printStackTrace();
        }
        return Collections.emptyMap();
    }
}
